using Microsoft.AspNetCore.Mvc;
using MVCDemo.Repository;
using MVCDemo.Models;
using System.Linq;
using MVCDemo.RequestParam;
namespace MVCDemo.Controllers
{
    public class ProductController:Controller
    {
        public IActionResult Index()
        {
            var Category=new EfRepository<Category>();
            var Cate=Category.Table.Where(x=>x.IsDeleted==false).FirstOrDefault();
            if(Cate==null){
                Category.Insert(new Category{
                    CategoryName="商品"
                });
            }
            var entity=new EfRepository<Product>();
            var entt=entity.Table.Where(x=>x.IsDeleted==false).ToList();
            return View(entt);
        }
        public IActionResult CreateOrEdit(int id)
        {
            var entity=new EfRepository<Product>();
            var entt=entity.Table.Where(x=>x.IsDeleted==false && x.Id==id).FirstOrDefault();
            return View(entt);
        }
        public IActionResult Save(ProductParam model)
        {
            var entity=new EfRepository<Product>();
            if(model.Id>0){
                var entt=entity.Table.Where(x=>x.IsDeleted==false && x.Id==model.Id).FirstOrDefault();
                entt.ProductName=model.ProductName;
                entt.Supplier=model.Supplier;
                entt.Price=model.Price;
                entt.Stock=model.Stock;
                entt.Remarks=model.Remarks;
                entity.Update(entt);
            }else{
                entity.Insert(new Product{
                    ProductName=model.ProductName,
                        Supplier=model.Supplier,
                        Price=model.Price,
                        Stock=model.Stock,
                        Remarks=model.Remarks,
                        CategoryId=1
                });
            }
            return Ok();
        }
        public IActionResult Delete(int id)
        {
            var entity=new EfRepository<Product>();
            entity.Delete(id);
            return RedirectToAction("Index");
        }
        public IActionResult Query(RequestQueryParam request)
        {
            var entity=new EfRepository<Product>();
            var KeyWord=request.KeyWord != null ? request.KeyWord.Trim() : "";
            var entt=entity.Table.Where(x=>x.IsDeleted==false).ToList();
            if (KeyWord.Length>0)
            {
                entt=entity.Table.Where(x=>x.IsDeleted==false && x.ProductName.Contains(request.KeyWord)).ToList();
            }
            return Json(entt);
        }
    }
}